package com.aspire.nm.component.miniServer.render;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;


import com.aspire.nm.component.util.ConstantConfig;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class NativeRender implements Render {
    
    @Override
    public String render(Object data, String source,String encode) throws RenderException {
        try {
            return renderTemplate(getNativeTemplate(source,encode),(Map<?,?>)data);
        } catch (TemplateException e) {
            throw new RenderException(e.toString());
        } catch (IOException e) {
            throw new RenderException(e.toString());
        }
    }

    
    private HashMap<String,Template> nativeTemplateMap = new HashMap<String,Template>();
    private Template getNativeTemplate(String templateName,String encode){
        if(nativeTemplateMap.get(templateName) == null){
            synchronized(NativeRender.class){
                if(nativeTemplateMap.get(templateName) == null){
                    Template template = null;
                    try {
                        template = new Template(null, ConstantConfig.getContentValue(templateName),null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    nativeTemplateMap.put(templateName, template);
                }
            }
        }
        return nativeTemplateMap.get(templateName);
    }
    
    
    private String renderTemplate(Template template,Map<?,?>root) throws TemplateException, IOException {
        String result;
        Writer out = new StringWriter();
        template.process(root, out);
        result = out.toString();
        out.flush();
        out.close();
        return result;
    }
}
